const Controller = require('egg').Controller
/**
 * @Controller 产品
 */
class productController extends Controller {

  /**
   *  添加产品
 */
  async insert() {
    const { ctx, service } = this
    const body = ctx.request.body
    ctx.validate({
      title: 'string',
      description: 'string',
      content: 'string'
    },body)
    const ret = await service.productService.insert(body)
    ctx.body = {
      code: 200,
      message: '添加成功'
    }
  }

  /**
   * 删除产品
 */
  async delete() {
    const { ctx,service } = this
    const body = ctx.request.body
    const Product = ctx.model.Product
    const File = ctx.model.File
    ctx.validate({
      id: 'string'
    },body)

    const _data = await Product.findById(body.id).populate('imgs')
    if(!_data) {
      ctx.throw('_id不正确！')
    }
    _data.remove()
    
    _data.imgs.forEach(item => {
      File.findByIdAndDelete(item._id)
      service.toolService.deleteDiskFile(item.link)
    });

    ctx.body = {
      code: 200,
      message: '删除成功'
    }
  }

  /**
   *  修改产品
 */
   async update() {
    const { ctx } = this
    const body = ctx.request.body
    const Product = this.ctx.model.Product

    ctx.validate({
      id: 'string',
      title: 'string',
      description: 'string',
      content: 'string'
    },body)

    //查找产品
    const _data = await Product.findByIdAndUpdate(body.id,Object.assign(body,{updatedAt: Date.now()})) 
    
    if(!_data) {
      ctx.throw(422,'_id不正确')
    }
    ctx.body = {
      code: 200,
      message: '修改成功'
    }
  }

  /**
  *  获取产品列表
 */
  async list() {
    const { ctx,service } = this
    const body = ctx.request.query
    ctx.validate({
      pageNum: 'string'
    },body)

    const data = await service.productService.getList(body)
    ctx.body = {
      code: 200,
      data
    }
  }
}

module.exports = productController 